import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Tree, Spin, Input, Modal, Empty, Tooltip, Icon, message } from 'antd';
import PubSub from 'pubsub-js';
import request from '@/utils/request';
import ScrollBar from '@/components/ScrollBar';
import IconFont from '@/components/IconFont';
import QueryCatalog from './components/QueryCatalog';
import QueryPlan from './components/QueryPlan';
// import QueryRule from './components/QueryRule';
import styles from './index.less';

const { TreeNode } = Tree;
const { Search } = Input;
const { confirm } = Modal;

const namespace = 'ruleConfig2';

const eventName = 'ruleConfig_tree';

function TreeMenu(props) {
  // 初始化加载loading
  const [loading, setLoading] = useState(false);
  // 组织树数据
  const [TreeData, setTreeData] = useState([]);
  // 选中点击的值
  const [selectedKeysArr, setSelectedKeysArr] = useState(['']);
  // 展示的树节点
  const [expandedKeys, setExpandedKeys] = useState([]);
  // 是否自动展开父节点
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  // 搜索
  const [searchValue, setSearchValue] = useState('');

  // ==== 组织树模态框 开始 ====
  // 修改、新增目录
  const [queryCatalogVisable, setQueryCatalogVisable] = useState(false);
  const [queryCatalogStatus, setQueryCatalogStatus] = useState('');
  const [catalogItem, setCatalogItem] = useState({});
  // 修改、新增方案
  const [queryPlanVisable, setQueryPlanVisable] = useState(false);
  const [queryPlanStatus, setQueryPlanStatus] = useState('');
  const [planItem, setPlanItem] = useState({});

  // === 结束 ===

  // 通过dva来传递选中节点的id,对右侧数据进行查找
  const savePassId = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/savePassId`,
      payload: params,
    });
  };

  // 初始化获取接口的Tree集合
  const queryTreeData = () => {
    setLoading(true);
    request('pmc/pms/RuleCfgController/showRuleTree', {
      method: 'POST',
    })
      .then(res => {
        if (res.success) {
          setTreeData(res.data);
        } else {
          message.error(res.errMessage);
        }
      })
      .always(() => setLoading(false));
  };

  useEffect(() => {
    queryTreeData();
    return savePassId('noId_noStatus');
  }, []);

  useEffect(() => {
    // 监听订阅
    PubSub.subscribe(`${eventName}.update`, () => {
      queryTreeData();
    });
    return () => {
      PubSub.unsubscribe(`${eventName}`);
    };
  });

  // 选中节点传递数据到右侧模块
  const passId = id => {
    savePassId(id);
  };
  // 选中节点
  const selectTreeNode = selectedKeys => {
    /* eslint-disable */
    selectedKeys.length > 0
      ? setSelectedKeysArr(selectedKeys)
      : setSelectedKeysArr(selectedKeysArr);
    /* eslint-enable */
    passId(selectedKeys.length > 0 ? selectedKeys.toString() : selectedKeysArr.toString());
  };

  const queryCatalog = (item, status) => {
    setCatalogItem(item);
    setQueryCatalogVisable(true);
    setQueryCatalogStatus(status);
  };

  // 遍历递归集合数据，渲染组织树
  const renderTreeNode = TreeArr => {
    if (TreeArr.length > 0) {
      return TreeArr.map(item => {
        const index = item.name.indexOf(searchValue);
        const beforeStr = item.name.substr(0, index);
        const afterStr = item.name.substr(index + searchValue.length);
        let title = '';
        /**
         * 不同层级操作状态不同
         */
        /* eslint-disable */
        // 规则
        if (item.type && item.type === 'rule') {
          title = (
            <span>
              {index > -1 ? (
                <span style={{ textDecoration: item.statucCd === '1100' ? 'line-through' : '' }}>
                  {beforeStr}
                  <span style={{ color: '#f50' }}>{searchValue}</span>
                  {afterStr}
                </span>
              ) : (
                <span style={{ textDecoration: item.statucCd === '1100' ? 'line-through' : '' }}>
                  {item.name}
                </span>
              )}
              <span className={styles.menu_tree_edit}>
                <Tooltip title="删除规则">
                  <Icon
                    type="delete"
                    className={styles.icon}
                    onClick={event => {
                      confirm({
                        content: `确定要删除【${item.name}】规则节点？`,
                        okText: '确定',
                        okType: 'danger',
                        cancelText: '取消',
                        onOk() {
                          request('pmc/pms/RuleCfgController/addEditViewRuleConfig', {
                            data: {
                              action_type: 'delete',
                              rule_id: item.id,
                            },
                          }).then(res => {
                            if (res.success) {
                              message.success('删除成功！');
                              queryTreeData();
                              setSelectedKeysArr(['']);
                              savePassId('noId_noStatus');
                            } else {
                              message.error(res.errMessage);
                            }
                          });
                        },
                      });
                    }}
                  />
                </Tooltip>
                {item.statucCd && item.statucCd === '1000' ? (
                  <Tooltip title="失效规则">
                    <Icon
                      type="exclamation-circle"
                      className={styles.icon}
                      onClick={event => {
                        confirm({
                          content: `确定要失效【${item.name}】节点？`,
                          okText: '确定',
                          cancelText: '取消',
                          onOk() {
                            request('pmc/pms/RuleCfgController/onInvalidateRule', {
                              data: {
                                ruleId: item.id,
                              },
                            }).then(res => {
                              if (res.success) {
                                message.success('失效成功！');
                                queryTreeData();
                              } else {
                                message.error(res.errMessage);
                              }
                            });
                          },
                        });
                      }}
                    />
                  </Tooltip>
                ) : (
                  <Tooltip title="生效规则">
                    <Icon
                      type="clock-circle"
                      className={styles.icon}
                      onClick={event => {
                        confirm({
                          content: `确定要生效【${item.name}】节点？`,
                          okText: '确定',
                          cancelText: '取消',
                          onOk() {
                            confirm({
                              content: `确定要生效【${item.name}】节点？`,
                              okText: '确定',
                              cancelText: '取消',
                              onOk() {
                                request('pmc/pms/RuleCfgController/onValidateRule', {
                                  data: {
                                    ruleId: item.id,
                                  },
                                }).then(res => {
                                  if (res.success) {
                                    message.success('生效成功！');
                                    queryTreeData();
                                  } else {
                                    message.error(res.errMessage);
                                  }
                                });
                              },
                            });
                          },
                        });
                      }}
                    />
                  </Tooltip>
                )}
              </span>
            </span>
          );
        } else if (item.type && item.type === 'directory') {
          // 目录
          title = (
            <span>
              {index > -1 ? (
                <span>
                  {beforeStr}
                  <span style={{ color: '#f50' }}>{searchValue}</span>
                  {afterStr}
                </span>
              ) : (
                <span>{item.name}</span>
              )}
              <span className={styles.menu_tree_edit}>
                <Tooltip title="编辑目录">
                  <Icon
                    type="edit"
                    className={styles.icon}
                    onClick={event => {
                      queryCatalog(item, 'edit');
                    }}
                  />
                </Tooltip>
                <Tooltip title="新增方案">
                  <Icon
                    type="plus-circle"
                    className={styles.icon}
                    onClick={event => {
                      setQueryPlanStatus('add');
                      setQueryPlanVisable(true);
                      setPlanItem(item);
                    }}
                  />
                </Tooltip>
                {item.children.length <= 0 ? (
                  <Tooltip title="删除目录">
                    <Icon
                      type="delete"
                      className={styles.icon}
                      onClick={event => {
                        confirm({
                          content: `确定要删除【${item.name}】目录节点？`,
                          okText: '确定',
                          okType: 'danger',
                          cancelText: '取消',
                          onOk() {
                            request('pmc/pms/RuleCfgController/addEditViewDirectory', {
                              data: {
                                action_type: 'delete',
                                directory_pid: item.pid,
                                directory_id: item.id,
                              },
                            }).then(res => {
                              if (res.success) {
                                message.success('删除成功！');
                                queryTreeData();
                                setSelectedKeysArr(['']);
                                savePassId('noId_noStatus');
                              } else {
                                message.error(res.errMessage);
                              }
                            });
                          },
                          onCancel() {},
                        });
                      }}
                    />
                  </Tooltip>
                ) : null}
              </span>
            </span>
          );
        } else if (item.type && item.type === 'plan') {
          // 方案

          title = (
            <span>
              {index > -1 ? (
                <span>
                  {beforeStr}
                  <span style={{ color: '#f50' }}>{searchValue}</span>
                  {afterStr}
                </span>
              ) : (
                <span>{item.name}</span>
              )}
              <span className={styles.menu_tree_edit}>
                <Tooltip title="编辑方案">
                  <Icon
                    type="edit"
                    className={styles.icon}
                    onClick={event => {
                      setQueryPlanStatus('edit');
                      setQueryPlanVisable(true);
                      setPlanItem(item);
                    }}
                  />
                </Tooltip>
                <Tooltip title="新增规则">
                  <Icon
                    type="plus-circle"
                    className={styles.icon}
                    onClick={event => {
                      props.goToStep(2, {
                        operType: 'add',
                        planInfo: { planName: item.name, planId: item.id },
                      });
                    }}
                  />
                </Tooltip>
                {item.children.length <= 0 ? (
                  <Tooltip title="删除方案">
                    <Icon
                      type="delete"
                      className={styles.icon}
                      onClick={event => {
                        confirm({
                          content: `确定要删除【${item.name}】方案节点？`,
                          okText: '确定',
                          okType: 'danger',
                          cancelText: '取消',
                          onOk() {
                            request('pmc/pms/RuleCfgController/addEditViewPlan', {
                              data: {
                                action_type: 'delete',
                                plan_id: item.id,
                              },
                            }).then(res => {
                              if (res.success) {
                                message.success('删除成功！');
                                queryTreeData();
                                setSelectedKeysArr(['']);
                                savePassId('noId_noStatus');
                              } else {
                                message.error(res.errMessage);
                              }
                            });
                          },
                          onCancel() {
                            console.log('Cancel');
                          },
                        });
                      }}
                    />
                  </Tooltip>
                ) : null}
              </span>
            </span>
          );
        }
        /* eslint-enable */
        return (
          <TreeNode
            icon={({ expanded }) => (
              /* eslint-disable */
              <IconFont
                type={
                  expanded
                    ? 'icon-folder-open'
                    : item.type && item.type === 'rule'
                    ? item.rel_type
                      ? `icon-${
                          item.rel_type === '0' ? 'bing' : item.rel_type === '1' ? 'yi' : 'hu'
                        }`
                      : 'icon-file'
                    : 'icon-folder'
                }
              />
              /* eslint-enable */
            )}
            title={title}
            key={`${item.id}_${item.type}`}
            isLeaf={item.type === 'rule' ? true : false}
            // 往组织树挂一个detaRef 可供外部获取选中的整个对象数据
            dataRef={item}
          >
            {item.children ? renderTreeNode(item.children) : null}
          </TreeNode>
        );
      });
    }
  };

  const onSearch = value => {
    // 为空搜索
    if (!value) {
      setExpandedKeys([]);
      setAutoExpandParent(false);
      setSearchValue('');
      return;
    }
    // 当前选中项的父节点
    setLoading(true);
    request('pmc/pms/RuleCfgController/showRuleTree', {
      data: {
        filterVal: value,
      },
    })
      .then(res => {
        if (res.success) {
          setExpandedKeys(res.data);
          setAutoExpandParent(true);
          setSearchValue(value);
        } else {
          message.error(res.errMessage);
        }
      })
      .always(() => {
        setLoading(false);
      });
  };

  const onExpand = expandedKeys => {
    setExpandedKeys(expandedKeys);
    setAutoExpandParent(false);
  };

  return (
    <div className={styles.menu}>
      <div className={styles.menu_search}>
        <Search style={{ marginBottom: 8 }} placeholder="搜索关键字" onSearch={onSearch} />
      </div>
      <ScrollBar autoHide autoHeight autoHeightMax={props.height - 100}>
        <Spin spinning={loading}>
          {TreeData.length > 0 ? (
            <Tree
              showIcon
              expandAction="false"
              className={styles.menu_tree}
              onSelect={selectTreeNode}
              selectedKeys={selectedKeysArr}
              onExpand={onExpand}
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
            >
              {renderTreeNode(TreeData)}
            </Tree>
          ) : (
            <Empty />
          )}
        </Spin>
      </ScrollBar>

      {queryCatalogVisable ? (
        <QueryCatalog
          visiable={queryCatalogVisable}
          close={() => {
            setQueryCatalogVisable(false);
          }}
          status={queryCatalogStatus}
          catalogItem={catalogItem}
        />
      ) : null}

      {queryPlanVisable ? (
        <QueryPlan
          visiable={queryPlanVisable}
          close={() => {
            setQueryPlanVisable(false);
          }}
          status={queryPlanStatus}
          planItem={planItem}
          queryTreeData={queryTreeData}
        />
      ) : null}
    </div>
  );
}

export default connect(() => ({}))(TreeMenu);
